import ForceUtil from '@/ForceUtil'
import PlayerUtil from '@/PlayerUtil'
import RandomUtil from '@/RandomUtil'
import SelectUtil from '@/SelectUtil'
import SyncUtil from '@/SyncUtil'

declare global {
    type shopItemTypes = 'base' | 'skill' | 'recipe' | 'sold'
    interface ShopItemModel extends t_shop_items {
        recipe?: string
        index?: number
    }
}

export default class UIShopModel {
    /** 普通出售的物品列表 */
    soldListMap: Map<shopItemTypes, ShopItemModel[]> = new Map()
    /** 技能出售列表，每个玩家相互独立，方便做不同的卡包 */
    skillSoldListMap: Map<string, ShopItemModel[]>[] = []
    constructor() {
        SyncUtil.onSyncObjData('shop_buy_item', UIShopModel.buyItemHandler)
        SyncUtil.onSyncData('shop_refresh_click', UIShopModel.refreshSkillItem)

        // 在玩家选择完毕难度之后再初始化 技能商店的数据
        se.on('GAME_HARD_SELECTED', this.initSkillShop.bind(this))
    }
    initSkillShop() {
        // 注册技能书的商品
        ForceUtil.forUserForce((p) => {
            let pid = GetPlayerId(p)
            let mp = (this.skillSoldListMap[pid] = new Map())
            mp.set('skill', this.randomSkillItems())
        })
    }
    static refreshSkillItem(p: player, pid: string) {
        let _this = UIManager.UIShopInstance.model
        let arr = _this.randomSkillItems()
        _this.skillSoldListMap[GetPlayerId(p)].set('skill', arr)
        PlayerUtil.addGoldState(p, -500)
        se.emit('背包数据变化', { p })
    }
    static buyItemHandler(
        p: player,
        {
            id,
            index,
            type,
            goldcost,
        }: { goldcost: number; id: string; index: number; type: shopItemTypes }
    ) {
        let backpackModel = UIManager.UIBakpack.model
        if (type == 'sold') {
            // 减去背包数据
            backpackModel.removeItemByIndex(index, p)
            // 增加金钱
            PlayerUtil.addGoldState(p, R2I(goldcost / 2))
        } else {
            // 减少金钱
            PlayerUtil.addGoldState(p, -goldcost)

            let h = SelectUtil.getAnHero(GetPlayerId(p))
            let item = CreateItem(id, GetUnitX(h), GetUnitY(h))
            // 技能分类与出售分类需要特殊处理
            if (type == 'skill') {
                // 删除对应的技能书
                UIManager.UIShopInstance.model.removeSkillItem(index, p)
                se.emit('背包数据变化', { db: null, p })
            }
            // 添加数据到背包
            backpackModel.addItem(item, p)
        }
    }
    removeSkillItem(index: number, p: player) {
        let arr = this.skillSoldListMap[GetPlayerId(p)].get('skill')
        arr[index] = null
    }
    randomSkillItems() {
        // 先取出所有人都能使用的技能
        let books = GlobalDB.ItemDB.normalSkillBooks
        // todo 添加额外的技能卡组 , 比如收费的卡组

        let arr: ShopItemModel[] = []
        // todo
        let max = 11 - game_hard_level // 难度越高，技能数量越少
        // 额外格子处理 , 比如商城道具增加的技能刷新格子或者成就奖励的格子
        // max += 0

        while (arr.length < max) {
            let index = RandomUtil.nextInt(0, books.length - 1)
            arr.push(books[index])
        }
        return arr
    }
    addItemToSoldList(type: shopItemTypes, item: ShopItemModel) {
        let list = this.soldListMap.get(type)
        if (!list) {
            list = [item]
            this.soldListMap.set(type, list)
        } else {
            list.push(item)
        }
    }
    getSoldList(type: shopItemTypes): ShopItemModel[] {
        return this.soldListMap.get(type) || []
    }
    transBakpack2Shop(items: UIBackPackItemModel[]) {
        if (items == null) return []
        let arr: ShopItemModel[] = []
        for (let i = 0; i < 30; i++) {
            let item = items[i]
            if (item == null) {
                arr[i] = null
                continue
            }
            arr[i] = {
                id: item.id,
                goldcost: item.price * item.count,
                Name: item.name,
                Art: item.art,
                Description: item.ubertip,
                CanBuy: 1,
                index: i,
            }
        }
        return arr
    }
}
